//
//  UUOrderDetailRateVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 25/02/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUOrderDetailRateVC.h"

#define Star_Count          (5)
#define Star_Interval       (13)

@interface UURateView : UIView

@property (nonatomic, assign) NSInteger rating;

@end

@implementation UURateView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    
    return self;
}

- (CGSize)intrinsicContentSize {
    CGFloat width = ([self starImageSize].width * Star_Count) + (Star_Count - 1) * Star_Interval;
    return CGSizeMake(width, [self starImageSize].height);
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    for (int i = 0; i < Star_Count; ++i) {
        CGRect imageRect = CGRectMake((Star_Interval + [self starImageSize].width) * i,
                                      0,
                                      [self starImageSize].width,
                                      self.height);
        if (i <= self.rating) {
            [[self starOnImage] drawInRect:imageRect];
        } else {
            [[self starOffImage] drawInRect:imageRect];
        }
    }
}

- (CGSize)starImageSize {
    return [self starOffImage].size;
}

- (UIImage *)starOnImage {
    return [UIImage imageNamed:@"OrderRateStarOn"];
}

- (UIImage *)starOffImage {
    return [UIImage imageNamed:@"OrderRateStarOff"];
}

@end

////////////////////////////////////////////////////////////

#define Tag_Interval            (10)
#define Tag_Font                ([UIFont systemFontOfSize:12])

@interface UUCommentTagView : UIView

@property (nonatomic, copy) NSArray<NSString *> *tags;
@property (nonatomic, copy) NSArray<NSString *> *currentTags;

@end

@implementation UUCommentTagView

- (void)layoutSubviews {
    [super layoutSubviews];
    
    [self setupTagsIfNeeded];
}

- (void)setupTagsIfNeeded {
    if (self.currentTags != self.tags) {
        self.currentTags = self.tags;
        [self setupTags];
    }
}

- (void)setupTags {
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat viewWidth = [UIScreen mainScreen].bounds.size.width * 0.8;
    
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(viewWidth);
    }];
    
    UIView *lastTag;
    __block CGFloat lastX = 0;
    for (NSString *tag in self.currentTags) {
        UILabel *tagLabel = [UILabel new];
        tagLabel.font = Tag_Font;
        tagLabel.text = tag;
        tagLabel.textColor = COMMON_TEXT_LIGHT_COLOR;
        tagLabel.textAlignment = NSTextAlignmentCenter;
        tagLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
        tagLabel.layer.borderWidth = 1;
        tagLabel.layer.borderColor = COMMON_TEXT_LIGHT_COLOR.CGColor;
        [self addSubview:tagLabel];
        
        CGFloat tagWidth = [self tagTextWidthForFont:tagLabel.font withText:tag];
        if (tagWidth > viewWidth) {
            tagWidth = viewWidth;
        }
        [tagLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            if (lastTag == nil) {
                lastX = tagWidth;
                make.left.mas_equalTo(0);
                make.top.mas_equalTo(0);
            } else if (lastX + Tag_Interval + tagWidth <= viewWidth) {
                lastX += (Tag_Interval + tagWidth);
                make.top.equalTo(lastTag.mas_top);
                make.left.equalTo(lastTag.mas_right).offset(Tag_Interval);
            } else {
                lastX = 0;
                make.left.mas_equalTo(0);
                make.top.equalTo(lastTag.mas_bottom).offset(Tag_Interval);
            }
            
            make.width.mas_equalTo(tagWidth);
            make.height.mas_equalTo(25);
        }];
        
        lastTag = tagLabel;
    }
}

- (CGSize)intrinsicContentSize {
    CGFloat viewWidth = [UIScreen mainScreen].bounds.size.width * 0.8;
    CGFloat lastY = 0;
    CGFloat lastX = 0;
    
    for (NSString *tag in self.tags) {
        CGFloat tagWidth = [self tagTextWidthForFont:Tag_Font withText:tag];
        if (tagWidth > viewWidth) {
            tagWidth = viewWidth;
        }
        if (lastX + lastY == 0) {
            lastY = 25;
            lastX = tagWidth;
        } else if (lastX + Tag_Interval + tagWidth <= viewWidth) {
            lastX += (Tag_Interval + tagWidth);
        } else {
            lastX = 0;
            lastY += (25 + Tag_Interval);
        }
    }
    
    return CGSizeMake(viewWidth, lastY);
}

- (CGFloat)tagTextWidthForFont:(UIFont *)font withText:(NSString *)text {
    return getTextSize(font, text, 999).width + 25;
}

@end

////////////////////////////////////////////////////////////

@interface UUOrderDetailRateVC ()

@property (nonatomic, weak) UURateView *rateView;

@end

@implementation UUOrderDetailRateVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    DKAssert(self.order != nil);
    
    [self setupUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"乘客评价";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = COMMON_TEXT_LIGHT_COLOR;
    titleLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(31);
        make.height.mas_equalTo(17);
        make.leading.trailing.mas_equalTo(0);
    }];
    
    UURateView *rateView = [UURateView new];
    rateView.rating = self.order.score;
    [self.view addSubview:rateView];
    
    [rateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(19);
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(-20);
    }];
    
    self.rateView = rateView;
    
    self.preferredContentSize = [self.view systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    
    NSArray<NSString *> *tagIds = [self.order.tagIds componentsSeparatedByString:@","];
    if (tagIds.count > 0) {
        NSArray<NSString *> *tagNames = [self constructTagNamesWithTagIds:tagIds];
        if (tagNames == nil) {
            WEAK_SELF();
            [GetRateManager() asyncUpdateRateWithCompleteBlock:^(NSError *error) {
                if (error == nil) {
                    NSArray<NSString *> *tagNames = [self constructTagNamesWithTagIds:tagIds];
                    if (tagNames != nil) {
                        [weakSelf showTagViewWithTags:tagNames];
                    }
                }
            }];
        } else {
            [self showTagViewWithTags:tagNames];
        }
    }
}

- (NSArray<NSString *> *)constructTagNamesWithTagIds:(NSArray<NSString *> *)tagIds {
    NSMutableArray<NSString *> *tagNames = [NSMutableArray arrayWithCapacity:tagIds.count];
    for (NSString *tagId in tagIds) {
        UURateModel *rateModel = [GetRateManager() fetchRateModelWithId:tagId];
        if (rateModel.name) {
            [tagNames addObject:rateModel.name];
        } else {
            return nil;
        }
    }
    
    return tagNames;
}

- (void)showTagViewWithTags:(NSArray<NSString *> *)tags {
    if (tags.count == 0) {
        return;
    }
    
    UUCommentTagView *tagView = [UUCommentTagView new];
    tagView.tags = tags;
    [self.view addSubview:tagView];
    
    for (NSLayoutConstraint *constraint in [self.view constraints]) {
        if (constraint.firstItem == self.view && constraint.firstAttribute == NSLayoutAttributeHeight && constraint.secondItem == nil) {
            [self.view removeConstraint:constraint];
        } else if (constraint.firstItem == self.rateView && constraint.firstAttribute == NSLayoutAttributeBottom && constraint.secondItem == self.view) {
            [self.view removeConstraint:constraint];
        }
    }
    
    [tagView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.rateView.mas_bottom).offset(19);
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(-19);
    }];
    
    self.preferredContentSize = [self.view systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
}

@end
